from rest_framework.response import Response
from rest_framework.views import APIView
from fdfs_client.client import Fdfs_client
from django.conf import settings
from rest_framework.response import Response
from django.http.response import HttpResponseRedirect


class UploadImageView(APIView):
    '''
        上传图片并返回地址
    '''
    def post(self, request):
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        res = client.upload_by_buffer(request.data.get('img').read())
        if res.get('Status') != 'Upload successed.':
            raise Exception('上传文件失败')
        file_id = res.get('Remote file_id')
        print(settings.FDFS_URL + file_id)
        return Response({'imgurl': settings.FDFS_URL + file_id})


class UploadCommentView(APIView):
    '''
        富文本文件上传保存
    '''
    def post(self, request):
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        data = request.FILES.get('upload').read()
        res = client.upload_by_buffer(data)
        if res.get('Status') != 'Upload successed.':
            raise Exception('上传文件失败')
        file_id = res.get('Remote file_id')
        CKEditorFuncNum = request.query_params.get('CKEditorFuncNum')
        from_address = 'http://www.tensquare.site:8080/'
        ret_url = from_address + '/upload_success.html?image_url=' + \
                  settings.FDFS_URL + file_id + '&CKEditorFuncNum=' + CKEditorFuncNum
        return HttpResponseRedirect(ret_url)
